import {h, reactive, Ref, ref} from 'vue';
import {Avatar} from 'ant-design-vue';
import type {DynamicProps} from '@pkg/types';
import {merge} from 'lodash-es';
import {ColEx} from '@/components/form/src/types';
import {FormActionType} from '@/components/form';
import {useMessage} from '@/hooks/web/useMessage';
import {useDesign} from '@/hooks/web/useDesign';
import {useTableMethods} from './useTableMethods';
import {BasicTableProps, TableActionType, useTable} from '@/components/table';
import {bus, filterObj, isNullOrUndefined} from '@pkg/utils';
import {request} from '@pkg/request/src';
import {RenderType} from '@pkg/setting';
import {render} from '@/hooks/render/renderUtils';
import {useUserStore} from '@/store/user';
import {basicProps} from "@/components/table/src/props";

//消息提示
const {createMessage, createConfirm} = useMessage();
const {handleExportXls, handleExportWord, handleImportXls} = useTableMethods();
// 定义Table所需参数
type TableProps = Partial<DynamicProps<BasicTableProps>>;
type UseTableMethod = TableActionType & {
  getForm: () => FormActionType;
};

let exportParams :any = reactive<Recordable>({});

// 定义封装Table参数类型
interface BaseTableOptions {
  // 样式作用域范围
  designScope?: string;
  // 【必填】表格参数配置
  tableProps: TableProps;
  // 分页
  pagination?: boolean;
  //接口对象
  api?: object;
  // 导出按钮配置
  exportConfig?: {
    url: string;
    // 导出文件名
    name?: string | (() => string);
    //导出参数
    params?: object;
  };
  // 导入按钮配置
  importConfig?: {
    url: string;
    // 导出成功后的回调
    success?: (fileInfo?: any) => void;
  };
  //操作按钮
  toolbar?: Recordable[];
}

interface IDoRequestOptions {
  // 是否显示确认对话框，默认 true
  confirm?: boolean;
  // 是否自动刷新表格，默认 true
  reload?: boolean;
  // 是否自动清空选择，默认 true
  clearSelection?: boolean;
}

/**
 * table封装
 *
 * @param options
 */
export function useBaseTable(options: BaseTableOptions) {
  let $design = {} as ReturnType<typeof useDesign>;
  //获取列表数据接口
  getListApi();
  //设置列渲染方式
  setColumnRender();
  if (options.designScope) {
    $design = useDesign(options.designScope);
  }
  const formConfig: any = options.tableProps.formConfig && options.tableProps.formConfig;
  if (formConfig) {
    const showExportButton = formConfig.showExportButton;
    if (!formConfig.exportFunc && showExportButton == true) {
      formConfig.exportFunc = onExportXls;
    }
  }
  const tableContext = useListTable(options.tableProps);

  const [, {getForm, reload, updateTableDataRecord, setLoading, getSelectRowKeys}, {selectedRowKeys, hasSelectedRows}] = tableContext;

  /**
   *  获取加载列表数据方法
   */
  function getListApi() {
    //获取列表数据接口地址
    const listUrl: any = options?.tableProps.listUrl;
    console.info(options)
    //当listUrl不为空且api未定义时
    if (listUrl && !options.tableProps.api) {
      options.tableProps.api = (params) =>
          request.get(
              {
                url: listUrl,
                params,
              },
              {successMessageMode: 'none'},
          );
    }
  }

  /**
   * 设置列的渲染方式
   */
  function setColumnRender() {
    //获取列配置
    const columns: any = options?.tableProps.columns;
    columns.forEach((item) => {
      const renderType = item.renderType;
      if (renderType) {
        switch (renderType) {
            //图片
          case RenderType.AVATAR:
            item.customRender = ({record}: Recordable) => {
              const avatar = record.avatar;
              return h(Avatar, {src: avatar});
            };
            break;
          case RenderType.DICT:
            item.customRender = render.renderDict;
        }
      }
    });
  }

  /**
   * 获取导出列
   */
  function getExportColumns() {
    const columns: any = options.tableProps.columns;
    const exportColumns: any = [];
    columns.forEach((column) => {
      //是否导出列,默认导出
      const isExport = column.isExport != undefined ? column.isExport : true;
      //渲染类型
      const renderType = column.renderType;
      if (isExport) {
        const exportColumn: any = {
          name: column.title,
          width: column.width / 5,
          key: column.dataIndex,
        };
        //是否合计列
        if (column.isStatistics) {
          exportColumn.isStatistics = column.isStatistics;
        }
        const code = column.dictCode || column.dataIndex;
        //是否字典
        if (renderType && renderType == RenderType.DICT) {
          exportColumn.dictData = column.dictData || useUserStore().getDictData[code];
        }
        //对应后端导出类型 1 是文本 2 是图片,3 是函数,10 是数字 默认是文本,暂时不支持图片导出
        if (column.renderType && column.renderType == 10) {
          exportColumn.type = column.renderType;
        }
        exportColumns.push(exportColumn);
      }
    });
    return exportColumns;
  }

  async function exportFile(params) {
    const {url, name}: any = options?.exportConfig ?? {
      url: options.tableProps.listUrl,
      name: options.tableProps.title,
    };
    if (url) {
      const title = typeof name === 'function' ? name() : name;
      return handleExportWord(title as string, url, filterObj(params));
    }

  }

  /**
   * 导出方法
   */
  async function onExportXls() {
    console.info("1111111111111111111",options)
    const {url, name, params}: any = options?.tableProps?.exportConfig;
    if (url) {
      const title = typeof name === 'function' ? name() : name;
      let paramsForm = await getForm().validate();
      const columns = getExportColumns();
      let searchInfo = options.tableProps.searchInfo;
      searchInfo=Object.assign({},searchInfo,exportParams)
      console.info('searchInfo', searchInfo)
      console.info('basicProps',basicProps)
      if (searchInfo) {
        paramsForm = Object.assign({}, searchInfo);
      }
      //如果参数不为空，则整合到一起
      if (params) {
        paramsForm = Object.assign({}, paramsForm, params, searchInfo);
      }
      if (selectedRowKeys.value && selectedRowKeys.value.length > 0) {
        paramsForm['selections'] = selectedRowKeys.value.join(',');
      }
      if (options.tableProps.handlerName) {
        paramsForm['handlerName'] = options.tableProps.handlerName;
      }
      if (columns) {
        paramsForm['columns'] = JSON.stringify(columns);
        paramsForm['isExport'] = true;
        paramsForm['title'] = name;
        paramsForm['fileName'] = name;
      }
      console.info('paramsForm', paramsForm)
      const formConfig: any = options.tableProps.formConfig && options.tableProps.formConfig;
      let isCheckExportTime = true
      if (!isNullOrUndefined(formConfig.isCheckExportTime)) {
        isCheckExportTime = formConfig.isCheckExportTime
      }
      let exportStartDateLabel = 'startDate'
      let exportEndDateLabel = 'endDate';
      let checkExportParams = {isCheckExportTime: isCheckExportTime}
      if (isCheckExportTime) {
        if (formConfig.exportStartDateLabel) {
          exportStartDateLabel = formConfig.exportStartDateLabel
        }
        if (formConfig.exportEndDateLabel) {
          exportEndDateLabel = formConfig.exportEndDateLabel
        }
        console.info(paramsForm.exportTimeType)
        let exportTimeType = paramsForm.exportTimeType
        if (!isNullOrUndefined(paramsForm.exportTimeType)) {
          console.info(paramsForm.exportTimeType)
          let exportTimeTypeOptions = formConfig.exportTimeTypeOptions
          if (!isNullOrUndefined(exportTimeTypeOptions)) {
            // @ts-ignore
            const exportTimeTypeOption: any = exportTimeTypeOptions.find((item:any) => item.exportTimeType == exportTimeType);
            if(!isNullOrUndefined(exportTimeTypeOption)){
              exportStartDateLabel = exportTimeTypeOption['startDate']
              exportEndDateLabel =  exportTimeTypeOption['endDate']
            }
          }
        }
        console.info('exportStartDateLabel', exportStartDateLabel)
        console.info('exportEndDateLabel', exportEndDateLabel)
        const startDate = paramsForm[exportStartDateLabel]
        const endDate = paramsForm[exportEndDateLabel]
        checkExportParams['startDate'] = startDate
        checkExportParams['endDate'] = endDate
      }
      console.info('checkExportParams', checkExportParams)
      return handleExportXls(title as string, url, filterObj(paramsForm));
    } else {
      createMessage.warn('没有传递 exportConfig.url 参数');
      return Promise.reject();
    }
  }

  /**
   * 导入 excel
   * @param file
   */
  function onImportXls(file) {
    const {url, success} = options?.importConfig ?? {};
    if (url) {
      return handleImportXls(file, url, success || reload);
    } else {
      createMessage.warn('没有传递 importConfig.url 参数').then((r) => {
      });
      return Promise.reject();
    }
  }

  /** 执行单个删除操作 */
  async function handleDelete(record) {
    //获取删除地址
    const delUrl: any = options?.tableProps.delUrl;
    //获取主键名
    const rowKey: any = options?.tableProps.rowKey;
    //return handleBatchDelete(api, { confirm: false, clearSelection: false })
    const params = {
      ids: record[rowKey],
    };
    return request.post({url: delUrl, params}).then(() => {
      reload();
    });
  }

  /** 执行post操作 */
  async function handlePost(url, params) {
    return request.post({url: url, params}).then(() => {
      reload();
    });
  }

  /**
   * 添加或者修改成功后刷新表格
   * @param isUpdate
   * @param values
   */
  async function handleSuccess({isUpdate, values}) {
    const rowKey: any = options?.tableProps.rowKey;
    if (isUpdate) {
      updateTableDataRecord(values[rowKey], values);
    } else {
      await reload();
    }
  }

  /**
   *  批量删除
   * @param api 请求api
   * @param options 是否显示确认框
   */
  async function handleBatchDelete() {
    const ids = getSelectRowKeys().join(',');
    //获取删除地址
    const delUrl: any = options?.tableProps.delUrl;
    if (ids) {
      const params = {
        ids: ids,
      };
      createConfirm({
        iconType: 'warning',
        title: '删除',
        content: '确定要删除吗？',
        onOk: () => {
          setLoading(true);
          //prettier-ignore
          request.post({url: delUrl, params}).then(() => {
            reload()
            selectedRowKeys.value = []
            hasSelectedRows.value = false
            setLoading(false)
          }).catch((err) => {
            setLoading(false)
          })
        },
        onCancel: () => {
        },
      });
    }
  }

  return {
    ...$design,
    onExportXls,
    exportFile,
    onImportXls,
    handleDelete,
    handlePost,
    handleBatchDelete,
    handleSuccess,
    tableContext,
  };
}

/**
 * useListTable 列表页面标准表格参数
 *
 * @param tableProps 表格参数
 */
export function useListTable(tableProps: TableProps): [
  (instance: any, formInstance: UseTableMethod) => void,
      TableActionType & {
    getForm: () => FormActionType;
  },
  {
    rowSelection: any;
    selectedRows: Ref<Recordable[]>;
    selectedRow: Ref<Recordable>;
    selectedRowKeys: Ref<any[]>;
    hasSelectedRows: any;
  },
] {
  // 自适应列配置
  const adaptiveColProps: Partial<ColEx> = {
    xs: 24, // <576px
    sm: 12, // ≥576px
    md: 12, // ≥768px
    lg: 8, // ≥992px
    xl: 8, // ≥1200px
    xxl: 6, // ≥1600px
  };
  const defaultTableProps: TableProps = {
    rowKey: 'id',
    // 使用查询条件区域
    useSearchForm: true,
    // 查询条件区域配置
    formConfig: {
      // 紧凑模式
      compact: true,
      // label默认宽度
      labelWidth: 120,
      // 按下回车后自动提交
      autoSubmitOnEnter: true,
      // 默认 row 配置
      rowProps: {gutter: 8},
      // 默认 col 配置
      baseColProps: {
        ...adaptiveColProps,
      },
      labelCol: {
        xs: 24,
        sm: 8,
        md: 6,
        lg: 8,
        xl: 6,
        xxl: 6,
      },
      wrapperCol: {},
      // 是否显示 展开/收起 按钮
      showAdvancedButton: true,
      // 超过指定列数默认折叠
      autoAdvancedCol: 3,
      // 操作按钮配置
      actionColOptions: {
        ...adaptiveColProps,
        style: {textAlign: 'left'},
      },
    },
    // 斑马纹
    striped: true,
    // 是否可以自适应高度
    canResize: true,
    // 表格最小高度
    minHeight: 300,
    // 点击行选中
    clickToRowSelect: false,
    // 是否显示边框
    bordered: true,
    // 是否显示序号列
    showIndexColumn: true,
    // 显示表格设置
    showTableSetting: false,
    // 表格设置
    tableSetting: {
      fullScreen: true,
    },
    // 是否显示操作列
    showActionColumn: true,
    // 操作列
    actionColumn: {
      width: 120,
      title: '操作',
      //是否锁定操作列取值 right ,left,false
      fixed: false,
      dataIndex: 'action',
    },
  };
  // 合并用户个性化配置
  if (tableProps) {
    // merge 方法可深度合并对象
    merge(defaultTableProps, tableProps);
  }

  // 发送请求之前调用的方法
  function beforeFetch(params) {
    console.info(11111111111111111)
    console.info(params)
    console.info(22222222222222222)
    // 额外参数赋值
    exportParams=params
    // handlerName赋值
    return Object.assign({handlerName: tableProps.handlerName ? tableProps.handlerName : ''}, params);
  }

  // 合并方法
  Object.assign(defaultTableProps, {beforeFetch});
  if (typeof tableProps.beforeFetch === 'function') {
    defaultTableProps.beforeFetch = function (params) {
      params = beforeFetch(params);
      // @ts-ignore
      tableProps.beforeFetch(params);
      return params;
    };
  }

  // 当前选择的行
  const selectedRowKeys = ref<any[]>([]);
  const hasSelectedRows = ref(false);
  // 选择的行记录
  const selectedRows = ref<Recordable[]>([]);
  const selectedRow = ref<Recordable>({});

  // 表格选择列配置
  const rowSelection: any = tableProps?.rowSelection ?? {};
  const defaultRowSelection = reactive({
    ...rowSelection,
    type: rowSelection.type ?? 'checkbox',
    // 选择列宽度，默认 50
    columnWidth: rowSelection.columnWidth ?? 50,
    selectedRows: selectedRows,
    selectedRow: selectedRow,
    selectedRowKeys: selectedRowKeys,
    hasSelectedRows: hasSelectedRows,
    onChange(...args) {
      selectedRowKeys.value = args[0];
      selectedRows.value = args[1];
      selectedRow.value = args[1][0];
      hasSelectedRows.value = args[0].length > 0;
      if (typeof rowSelection.onChange === 'function') {
        rowSelection.onChange(...args);
      }
    },
  });
  delete defaultTableProps.rowSelection;
  const [register, method] = useTable(defaultTableProps);
  const {reload, updateTableDataRecord, setLoading, getSelectRowKeys} = method;
  return [
    register,
    {...method},
    {
      selectedRows,
      selectedRow,
      selectedRowKeys,
      hasSelectedRows,
      rowSelection: defaultRowSelection,
    },
  ];
}
